package xuesm.proxy.dynamic.facemeng;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author: xuesm
 * @Description: 加载类
 * @Date: Create in 13:02 2019/4/3
 */
public class FMClassLoader extends ClassLoader {

	private File classPathFile;

	public FMClassLoader(){
		String classPath = FMClassLoader.class.getResource("").getPath();
		this.classPathFile = new File(classPath);
	}


	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {

		String className = FMClassLoader.class.getPackage().getName() + "." + name;
		if (classPathFile != null){
			File classFile = new File(classPathFile, name.replaceAll("\\.","/") + ".class");
			if (classFile.exists()){
				FileInputStream fis = null;
				ByteArrayOutputStream bos = null;
				try {
					fis = new FileInputStream(classFile);
					bos = new ByteArrayOutputStream();
					byte[] buff = new byte[1024];
					int len;
					while ((len = fis.read(buff)) != -1){
						bos.write(buff, 0, len);
					}
					return defineClass(className, bos.toByteArray(), 0, bos.size());
				}catch (Exception e){
					e.printStackTrace();
				}finally {
					if (fis != null){
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (bos != null){
						try {
							bos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return super.findClass(name);
	}
}
